﻿//  Copyright (c) 2010 Ray Liang (http://www.dotnetage.com)
//  Dual licensed under the MIT and GPL licenses:
//  http://www.opensource.org/licenses/mit-license.php
//  http://www.gnu.org/licenses/gpl.html

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Xml;

namespace DNA.OpenAPI.Ping
{
    public class PingbackSender
    {
        #region Public Methods

        public static bool Send(Uri sourceUri,Uri targetUri,Uri pingUri)
        {
            if ((sourceUri == null) || (targetUri == null))
                return false;
            
            var request = (HttpWebRequest)WebRequest.Create(pingUri);
            request.Method = "POST";
            request.ContentType = "text/xml";
            request.ProtocolVersion = HttpVersion.Version11;
            request.Headers["Accept-Language"] = "en-us";
            WriteXmlRpcPingMethodToRequest(sourceUri, targetUri, request);
            var response = (HttpWebResponse)request.GetResponse();
            response.Close();
            return true;
        }

        private static void WriteXmlRpcPingMethodToRequest(Uri sourceUrl,Uri targetUrl,HttpWebRequest request)
        {
            var stream = request.GetRequestStream();
            using (var writer = new XmlTextWriter(stream, Encoding.ASCII))
            {
                writer.WriteStartDocument(true);
                writer.WriteStartElement("methodCall");
                writer.WriteElementString("methodName", "pingback.ping");
                writer.WriteStartElement("params");

                writer.WriteStartElement("param");
                writer.WriteStartElement("value");
                writer.WriteElementString("string", sourceUrl.ToString());
                writer.WriteEndElement();
                writer.WriteEndElement();

                writer.WriteStartElement("param");
                writer.WriteStartElement("value");
                writer.WriteElementString("string", targetUrl.ToString());
                writer.WriteEndElement();
                writer.WriteEndElement();

                writer.WriteEndElement();
                writer.WriteEndElement();
            }
        }

        #endregion
    }
}